<template>
  <div class="wrapper">
    <table border="1px solid #ccc;" style="width: 400px">
      <thead>
        <tr>
          <th>名称</th>
          <th>数量</th>
          <th>单价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in data" :key="index" align="center">
          <td>{{ item.name }}</td>
          <td>
            <button @click="addAndSub(item, false)">+</button>
            {{ item.num }}
            <button @click="addAndSub(item, true)">-</button>
          </td>
          <td>{{ item.num * item.price }}</td>
          <td><button @click="del(index)">删除</button></td>
        </tr>
      </tbody>
      <tfoot>
        <tr align="center">
          <td></td>
          <td></td>
          <td></td>
          <td>合计：{{ $total }}</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from "vue";
type Data = {
  name: string;
  num: number;
  price: number;
};
const data = reactive<Data[]>([
  {
    name: "雨伞",
    num: 1,
    price: 100,
  },
  {
    name: "衣服",
    num: 1,
    price: 200,
  },
  {
    name: "鞋子",
    num: 1,
    price: 300,
  },
  {
    name: "裤子",
    num: 1,
    price: 400,
  },
]);

const addAndSub = (item: Data, type: boolean): void => {
  if (item.num < 99 && !type) {
    item.num++; // 加
  }
  if (item.num > 1 && type) {
    item.num--; // 减
  }
};

const del = (index: number): void => {
  data.splice(index, 1);
};

let $total = ref<number>(0);
$total = computed<number>(() => {
  return data.reduce((prev, next): number => {
    return prev + next.num * next.price;
  }, 0);
});
</script>

<style scoped></style>
